package com.xiaoge.system.service.impl;

import com.alibaba.fastjson.JSON;

import com.xiaoge.system.entity.Blog;
import com.xiaoge.system.mapper.BlogMapper;
import com.xiaoge.system.service.BlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaoge
 * @since 2021-04-13
 */
@Service

public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements BlogService {
    @Autowired
    private RestHighLevelClient getEsClient;
    @Autowired
    private BlogMapper blogMapper;

    //实现搜索
    public List<Map<String,Object>> searchByKeyword(String keyword, int pageNum, int pageSize) throws IOException {
        //条件搜索
        SearchRequest searchRequest = new SearchRequest("jd_goods");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //分页
        sourceBuilder.from(pageNum);
        sourceBuilder.size(pageSize);

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        //高亮
        sourceBuilder.highlighter(highlightBuilder);


        //精准拼配
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        searchRequest.source(sourceBuilder);
        SearchResponse response = getEsClient.search(searchRequest, RequestOptions.DEFAULT);

        List<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit documnetFiled : response.getHits().getHits()) {
            Map<String, HighlightField> highlightFields = documnetFiled.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            Map<String, Object> sourceAsMap = documnetFiled.getSourceAsMap();
            if (title != null) {
                String n_text = "";
                Text[] fragments = title.getFragments();
                for (Text text : fragments) {
                    n_text += text;
                }
                sourceAsMap.put("title", n_text);
            }

            //解析高亮
            list.add(sourceAsMap);
        }
        return list;
    }

    public Boolean parseContent(List<Blog> contents) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        for (int i = 0; i<contents.size();i++){
            bulkRequest.add(new IndexRequest("blog").source(JSON.toJSONString(contents.get(i)),
                    XContentType.JSON));
        }
        BulkResponse bulk = getEsClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulk.hasFailures();

    }

    @Override
    public int insertBlog(Blog blog) throws IOException {
        blog.setCreatime(new Date());
        blog.setStatus(0);
        blog.setViews(0L);
        int row = this.baseMapper.insert(blog);
        return row;
    }

    @Override
    public List<Map<String, Object>> queryAllCategory() {
        return this.blogMapper.queryAllCategory();
    }
}
